import { Toast } from "vant";
// import QRCode from "qrcode";
import yz_pay from "components/ui_components/yz_pay";
import voucherPay from "./components/voucherPay";
import { yzPay } from "../../../utils/yz_pay"; //引入支付方法

var self = null;
export default {
  mixins: [yzPay],
  beforeRouteLeave: function(to, from, next) {
    if (to.name == "HotelGoodsOrder") {
      this.$dialog
        .confirm({ message: "您还没完成支付，确认离开?" })
        .then(() => {
          self.$router.push(self.fun.getUrl("home", {}));
          next();
        })
        .catch(() => {
          next(false);
        });
    } else {
      next();
    }
  },
  data() {
    return {
      balance: 0,
      payParams: "",
      info_form: {},
      order_sn: "",
      money: "",
      buttons: [],
      typename: "",
      pay_sn: "订单编号",
      order_pay_id: "",
      uid: "",
      // 余额字样
      balanceLang: this.fun.getBalanceLang(),

      is_cps: false,
      //区别周边游支付和正常支付
      payTag:'',
      showVoucher: false,//代金券支付

      radioCurrency: null,

      //  支付协议弹窗
      showPaymentAgreement: false,
      mini_payment_agreement: '',
      IPAWatchTimeNum: 5,
      IPAToLower: false,//是否已触底
      disabledIPA: true, //是否已完成阅读支付协议
      integral: 0
    };
  },
  methods: {
    onReadOrderPay(){
      if(this.$route.params.tag == 'auth'){
        this.money = this.$route.params.price;
        this.authPayButton();
        return;
      }
      if(this.$route.name == 'idShopApplyPay'){
        this.money = this.$route.params.price;
        this.order_sn = this.$route.query.ordersn;
        this.idShopApplyButton();
        return
      }
      if(this.$route.query.tag == 'tourAround'){
        // this.money = this.$route.params.price;
        this.order_sn = this.$route.query.ordersn;
        this.payTag = this.$route.query.tag;
        this.tourAroundOrder(this.$route.query.api);
        return;
      }
      if (this.$route.params.iscps) {
        this.is_cps = true;
      }
      if (this.$route.params.status == 2) {
        this.order_ids = decodeURI(this.$route.params.order_ids); // JSON.parse(this.$route.params.order_ids)
      } else {
        this.order_ids = this.$route.params.order_ids;
        if (this.$route.params.route) {
          this.pageUrl = this.$route.params.route;
        }
      }
      self = this;
      let globalParameter = JSON.parse(window.localStorage.getItem("globalParameter"))||{};
      if (globalParameter && globalParameter.is_open_shop_esign_v2 == "1") {
        this.getShopSignV2();//商城电子合同2.0
      } else if (globalParameter && globalParameter.is_open_shop_esign == "1") {
        this.getShopSign();
      } else {
        this.getMultipleOrderInfo();
      }
    },
    // 多订单合并支付获取信息接口方法
    getMultipleOrderInfo() {
      // order.pay.wechatPay
      if (window.self !== window.top) {
        // console.log("这是在iframe环境打开");
        let isQRPay = window.sessionStorage.getItem('isQRPay')||false;
        if(isQRPay) this.isQRPay = true;
      }
      let _url = "order.merge-pay";
      try {
        if (!this.fun.isTextEmpty(this.$route.query.api) && this.$route.query.api != "order.operation.pay") {
          _url = this.$route.query.api;
          console.log(this.$route.query.api);
          console.log(_url);
        }
      } catch (error) {
        console.log(error);
      }

      let json = {
        order_ids: this.order_ids,
        pid: this.$route.query.pid ? this.$route.query.pid : this.uid
      };
      if(this.isQRPay) json.pc = 1;

      if (this.fun.isCPS() && this.fun.isCPSAPPI()) {
        json.wechat_app_pay_type = "cps";
      }
      console.log(this.$route.params.store_id);
      if(this.$route.params.store_id){
        json.store_id = this.$route.params.store_id;
      }
      if(_url=="plugin.water-machine.frontend.consumer.no-card-goods.index"){
        json.device_no = this.$route.query.device_no;
      }

      $http
        .get(_url,json,"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              this.order_sn = response.data.order_pay.pay_sn;
              this.balance = Number(response.data.member.credit2).toFixed(2);
              this.money = Number(response.data.order_pay.amount).toFixed(2);
              this.uid = response.data.order_pay.uid;
              this.order_pay_id = response.data.order_pay.id; // 支付id
              this.integral = response.data.order_pay.integral
              if(this.isQRPay){
                let isQRPayBtn = [57,28,85,2,120];//可以进行二维码扫码支付的支付方式
                this.buttons = response.data.buttons.filter(item => isQRPayBtn.includes(item.value));
              } else {
                this.buttons = response.data.buttons;
              }

              this.typename = response.data.typename;
              if(response.data.buttons && response.data.buttons.length == 0){
                this.$dialog.alert({message:"平台未开启任何支付方式，请联系客服！"});
              }
              if(response.data.mini_payment_agreement !== '') {
                this.mini_payment_agreement = response.data.mini_payment_agreement;
                this.$toast({ message: '请下滑阅读协议', duration: 3000 });
                this.showPaymentAgreement = true;
                this.$nextTick(() => {
                  this.$refs.scrollContent.scrollTop = 0;
                  this.$refs.scrollContent.addEventListener('scroll', this.handleScrollPA);
                });
                this.IPAInterval = setInterval(() => {
                  this.IPAWatchTimeNum = this.IPAWatchTimeNum - 1;
                  if (this.IPAWatchTimeNum <= 0 ) {
                    clearInterval(this.IPAInterval); // 达到条件后清除计时器
                    this.IPAWatchTimeNum = 0;
                    if(this.IPAToLower) {
                      this.disabledIPA = false;
                    }
                  }
                }, 1000);
              }

            } else {

              this.$dialog
                .confirm({ message: response.msg })
                .then(() => {
                  if(this.$route.params.orderType){
                    this.$router.replace(this.fun.getUrl("orderlist",{status:0,orderType:this.$route.params.orderType}));
                  }else{
                    this.$router.replace(this.fun.getUrl("home"));
                  }
                })
                .catch(() => {});
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    //周边游支付
    tourAroundOrder(api) {
      let json = {
        order_sn: this.order_sn
      };
      $http
        .get(api,json,"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              let data = response.data;
              this.order_sn = data?.order?.order_sn;
              this.balance = Number(response.data.credit2).toFixed(2);
              this.money = Number(data?.order?.order_price).toFixed(2);
              this.uid = data.order?.id;
              this.order_pay_id = data.order?.id; // 支付id
              this.buttons = data.buttons;
              this.typename = data.typename;
              if(response.data.buttons && response.data.buttons.length == 0){
                this.$dialog.alert({message:"平台未开启任何支付方式，请联系客服！"});
              }
            } else {

              this.$dialog
                .confirm({ message: response.msg })
                .then(() => {
                  this.$router.replace(this.fun.getUrl("home"));
                })
                .catch(() => {});
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    CheckTypeConfirm(data) {
      if(this.$route.name == 'idShopApplyPay'){
        this.idShopPay(data.value)
        return
      }
      if (this.$route.query.tag == 'tourAround') {
        if (!data.need_password) {
          this.ordinary(this.order_sn, data.value, data);
        } else {
          this.rechargePay(data.value,  this.order_sn, this.order_sn, "tourAroundPay",data); //走支付密码，不走周边游支付，避免重复支付
        }

      }else{
        // 这是yz_pay的混入直接走商城订单
        this.confirm(data);
      }
    },
    ordinary(order_sn,pay_type,data) { //周边游支付功能
      let query = {
        order_sn: order_sn,
        pay_type: pay_type
      };
      $http
        .post("plugin.travel-around.frontend.payment.payment.pay",query,"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              console.log('普通支付调用');
              // 你这里走完新接口就走混入yz_pay的充值方法
              this.rechargePay(pay_type, response, order_sn, "tourAroundPay",data);
            } else {
              this.$dialog.alert({message:response.msg});
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    getShopSign() {
      $http.get("plugin.shop-esign.frontend.contract.get-order-contract", { order_ids: this.order_ids }, "...").then(
        response => {
          if (response.result === 1) {
            let flag = false;
            response.data.map(item => {
              if (item.need_sign === 1 && item.contract_id && !flag) {
                flag = true;
                this.$dialog
                  .alert({ message: `您的订单(订单号:${item.order_sn})在支付前需要签署电子合同` })
                  .then(() => {
                    this.$router.push(this.fun.getUrl("signPagePlu", { id: item.contract_id }, { fromOrder: 1 }));
                  })
                  .catch(() => {});
              }
            });

            if (!flag) {
              this.getMultipleOrderInfo();
            }
          } else {
            this.getMultipleOrderInfo();
          }
        });
    },
    getShopSignV2() {
      $http.get("plugin.shop-esign-v2.frontend.controllers.index.needSign", { order_id: this.order_ids }, "...").then(
        response => {
          if (response.result === 1) {
            if (response.data.need_sign) {
              this.$dialog
                .alert({ message: `您的订单在支付前需要签署电子合同` })
                .then(() => {
                  this.$router.push(this.fun.getUrl("shopSignIndexV2", { scene: 1,order_id: this.order_ids }));
                })
                .catch(() => {});
              return;
            }
            this.getMultipleOrderInfo();
          } else {
            this.getMultipleOrderInfo();
          }
        });
    },
    authPay(payId){
      let that = this;
      $http
        .get("plugin.real-name-auth.frontend.pay.pay",{ pay_id:payId,pay_amount:this.money,pay_sn:this.order_sn },"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              if(payId == '54'){
                this.$router.go(-1);
                return;
              } else {
                console.log(payId);
                console.log('11111');
                that.rechargePay(payId,response,response.data.pay_sn);
              }
            } else {
              this.$dialog.alert({message:response.msg});
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    idShopApplyButton(value){
      $http
        .get("plugin.project-party.frontend.controllers.child-id.getButtons",{price:this.$route.params.price,pay_sn:this.$route.query.ordersn},"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              this.buttons = response.data.buttons;
            } else {
              this.$dialog.alert({message:response.msg});
              this.$router.go(-1)
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    authPayButton(){
      $http
        .get("plugin.real-name-auth.frontend.pay.getPayButton",{},"...")
        .then(
          (response)=> {
            if (response.result == 1) {
              this.order_sn = response.data.pay_sn;
              this.order_pay_id = response.data.order_pay&&response.data.order_pay.id||0; // 支付id
              this.buttons = response.data.buttons;
            } else {
              this.$dialog.alert({message:response.msg});
            }
          },
          (response)=> {
            Toast(response.msg);
          }
        );
    },
    passwordVerSucceed(password, payTag = "", payType = ""){
      if(payType == 3) {
        this.balancePay(password,payTag,payType);//余额支付
      } else {
        this.newPayQuick({payment_password: password});
      }
    },
    handleScrollPA(event) {
      // 判断是否触底的逻辑
      const isReachBottom = event.target.scrollHeight - event.target.scrollTop - 20 < event.target.clientHeight;
      if (isReachBottom) {
        this.scrolltolowerPA();
      }
    },
    scrolltolowerPA(){
      this.IPAToLower = true;
      if(this.IPAToLower && this.IPAWatchTimeNum <= 0) {
        this.disabledIPA = false;
      }
    },
    payArtNext(){
      if(this.disabledIPA) return;
      this.showPaymentAgreement = false;
    },
    cancelPA(){
      if(this.IPAInterval) clearInterval(this.IPAInterval);
      try {
        this.$router.go(-1);
      } catch (error) {
        this.$router.push(this.fun.getUrl("home", {}));
      }
    },
  },
  activated() {
    this.onReadOrderPay();
  },
  deactivated(){
    if(this.$route.name == "idShopApplyPay" || this.$route.name == "Sub_account_buy" || this.$route.name == "idShop_apply"){
      this.releaseChildId();
    }
    if(this.IPAInterval) clearInterval(this.IPAInterval);
    this.$refs.scrollContent.removeEventListener('scroll', this.handleScrollPA);
  },
  beforeDestroy() {
    if(this.IPAInterval) clearInterval(this.IPAInterval);
    this.$refs.scrollContent.removeEventListener('scroll', this.handleScrollPA);
  },
  components: {
    yz_pay,voucherPay
  }
};
